import { URL, URLSearchParams } from 'url';
import http from 'http';
import { RouteOption, RouteHandler, subRoute } from "../../type/routertype"
import { error, log } from 'console';

class Router {
    //需要改进 
    //实现子路由的插入 

    /**
     * 已注册的路由列表
     */
    private Router: Array<RouteOption> = [];

    /**
     * 
     * @param req 请求内容  通过路由路径和请求方法找路由
     * @returns 返回其对应的路由
     */
    public findRoute(req: http.IncomingMessage): subRoute | RouteOption {
        // 获取路由的路径和请求方法
        let requestUrl = new URL(`http://${req.headers.host}${req.url}`, 'http://localhost');
        let requestUrlpathname = requestUrl.pathname
        let requestMethod = req.method as string;

        //处理带参数的url
        const queryParams = new URLSearchParams(requestUrl.search);
        const params: Record<string, string> = {};
        queryParams.forEach((value, key) => {
            params[key] = value;
        });

        //  从已经存储的路由中找到目标路由
        for (let index = 0; index < this.Router.length; index++) {
            let item = this.Router[index];
            if (item.path === requestUrlpathname && item.method === requestMethod) {
                item.params = params;
                return item
            }
            if (item.subRoute.length !== 0 && item.path.split("/").filter(Boolean)[0] === requestUrlpathname.split("/").filter(Boolean)[0]) {
                for (let i = 0; i < item.subRoute.length; i++) {
                    let element = item.subRoute[i];
                    if (element.path === requestUrlpathname && element.method === requestMethod) {
                        element.params = params;
                        return element
                    }
                }
            }
        }
    }

    /**
     * 注册路由
     * @param path 路由路径
     * @param method 路由请求形式 get? post? ...
     * @param handler 路由路径对应的方法
     */

    public registerRoute(path: string, method: string, handler: RouteHandler): void {
        let pathArray = path.split("/").filter(Boolean);        //["qwe","qwe","qwe"]
        if (pathArray.length === 0) {           //路由为 / 时，拒绝注册
            throw error("path can not be / !")
        }
        if (this.Router.length === 0) {
            this.addRouteToRouter(path, method, handler, {}, [])
            return
        }
        //注册子路由
        for (let index = 0; index < this.Router.length; index++) {
            if (this.Router[index].path.split("/")[1] === pathArray[0]) {
                let params: Record<string, string> = {}
                this.Router[index].subRoute.push({ path, method, handler, params })
                return
            }
        }
        this.addRouteToRouter(path, method, handler, {}, [])
    }

    /**
     * addRouteToRouter 把路由添加进路由器
     */
    private addRouteToRouter(path: string, method: string, handler: RouteHandler, params?: Record<string, string>, subRoute?: []) {
        this.Router.push({ path, method, handler, params, subRoute })
    }

    /**
     * 
     * @param req 需要获取的url参数的req请求
     * @returns    返回url中的参数
     */
    public getUrlParams(req: http.IncomingMessage): Record<string, string> {
        return this.findRoute(req).params
    }

    /**
     * 创建服务
     * @param post 端口号，默认为3000
     * @param callback 一个回调
     */
    public createServer(post?: number, callback?: () => void): void {
        if (!post) post = 3000
        log(this.Router)
        http.createServer((req: http.IncomingMessage, res: http.ServerResponse) => {
            let route = this.findRoute(req);
            // log("123", route)
            if (route) {
                route.handler(req, res);
            } else {
                res.writeHead(404, { 'Content-Type': 'text/plain' });
                res.end('Not Found');
            }
        }).listen(post, callback)
        console.log(`Server is running on port ${post}...`);
    }
}
export default Router;